<template>
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" label-width="auto" class="demo-form-inline">
        <el-form-item label="设备编码">
          <el-input v-model="searchParam.equipmentCode" placeholder="请输入设备编码" clearable style="width: 180px"/>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="searchParam.equipmentName" placeholder="请输入设备名称" clearable style="width: 180px"/>
        </el-form-item>
        <el-form-item label="维修部门" prop="maintenanceDepartmentId">
          <el-tree-select v-model="searchParam.maintenanceDepartmentId" :data="workOptions" check-strictly
                          :render-after-expand="false"
                          :props="{
									children: 'children',
									label: 'orgName',
									value: 'id',
								}" style="width: 250px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch()">查询</el-button>
          <el-button icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd">新建</el-button>
          <!-- 添加列按钮 -->
          <!--					<el-button :icon="Plus" @click="showAddColumnDialog = true" type="primary">表头列配置</el-button>-->
          <el-button type="primary" @click="printClick" :disabled="multipleSelection.length == 0">二维码打印</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 325px)"
                @selection-change="handleSelectionChange" :loading="isLoading">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope"> {{
              (paginationParams.current - 1) * paginationParams.pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentCode" label="设备编码" align="center" min-width="200"/>
        <el-table-column prop="equipmentName" label="设备名称" align="center" min-width="200"/>
        <!-- <el-table-column label="设备来源" align="center" min-width="100">
          <template #default="scope"> {{ getTypeName(scope?.row?.equipmentType) }} </template>
        </el-table-column> -->
        <el-table-column prop="equipmentSource" label="设备分类" align="center" width="200"/>
        <el-table-column prop="leaveCode" label="出厂编号" align="center" min-width="200"/>
        <!-- 动态列渲染 -->
        <el-table-column v-for="col in columns" :key="col.tableKey" :prop="col.tableKey" :label="col.tableChineseKey"
                         align="center"/>
        <el-table-column prop="deviceId" label="外围系统编号" align="center" width="200"/>
        <el-table-column prop="orgAbbreviation" label="工厂/车间" align="center" width="200"/>
        <el-table-column prop="maintenanceDepartmentIdName" label="维修部门" align="center" width="200"/>
        <el-table-column label="操作" align="center" fixed="right" min-width="180">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" size="small" plain text :icon="Edit">编辑</el-button>
            <el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="paginationParams.current"
                       v-model:page-size="paginationParams.pageSize" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle">
      <el-form :model="formData" label-width="130px" ref="ruleFormRef" :rules="rules">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="设备编码" required prop="equipmentCode">
              <el-input v-model="formData.equipmentCode" placeholder="请输入设备编码" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" required prop="equipmentName">
              <el-input v-model="formData.equipmentName" placeholder="请输入设备名称" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="设备来源" required prop="equipmentType">
              <el-select v-model="formData.equipmentType" clearable style="width: 300px">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="设备分类" required prop="equipmentSource">
              <el-input v-model="formData.equipmentSource" placeholder="请输入设备分类" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出厂编号" required prop="leaveCode">
              <el-input v-model="formData.leaveCode" placeholder="请输入出厂编号" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外围系统编号">
              <el-input v-model="formData.deviceId" placeholder="请输入外围系统编号" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工厂/车间" prop="organizationId" required>
              <el-tree-select v-model="formData.organizationId" :data="workOptions" check-strictly
                              :render-after-expand="false"
                              :props="{
									children: 'children',
									label: 'orgName',
									value: 'id',
								}" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修部门" prop="maintenanceDepartmentId">
              <el-tree-select v-model="formData.maintenanceDepartmentId" :data="workOptions" check-strictly
                              :render-after-expand="false"
                              :props="{
									children: 'children',
									label: 'orgName',
									value: 'id',
								}" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <!-- 动态字段在弹窗中渲染 -->
          <el-col :span="12" v-for="col in columns" :key="col.tableKey">
            <el-form-item :label="col.tableChineseKey" :prop="col.tableKey">
              <el-input v-model="formData[col.tableKey]" :placeholder="`请输入${col.tableChineseKey}`"
                        style="width: 300px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog" title="管理列信息">
      <!-- 表格增删改查 -->
      <el-button :icon="Plus" @click="showAddColumnDialog2 = true; columnDialogTitle = '新建'" type="primary"
                 style="margin-bottom: 20px;">新建列
      </el-button>
      <el-table :data="columns">
        <el-table-column prop="tableChineseKey" label="列名称" align="center"/>
        <el-table-column prop="tableKey" label="列编码" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button @click="editColumn(scope.row, scope.$index)" size="small" icon="Edit">编辑</el-button>
            <el-button @click="deleteColumn(scope.row, scope.$index)" size="small" type="danger" icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="showAddColumnDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog2" :title="columnDialogTitle">
      <el-form>
        <el-form-item label="列名称">
          <el-input v-model="newColumn.tableChineseKey" placeholder="请输入列名称"/>
        </el-form-item>
        <el-form-item label="列Key">
          <el-input v-model="newColumn.tableKey" placeholder="请输入列Key"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddColumnDialog2 = false">取消</el-button>
        <el-button type="primary" @click="addColumn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue';
import {useEquipmentData} from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {ref} from 'vue';
import {lineAll} from '@/api/baseData/productionLine';
import {getCurrentInstance} from "vue";

const {
  searchParam,
  paginationParams,
  pageTotal,
  paginatedData,
  searchFields,
  handleSearch,
  handleSizeChange,
  handleCurrentChange,
  addEquipment,
  deleteEquipment,
  isLoading,
  ruleFormRef,
  rules,
  formData
} = useEquipmentData();
const isEdit = ref(false);
const showCrud = ref(false);
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});
onMounted(() => {
  getColumnsList();
  getOptions();
});

const workRoomList = ref([]);

// 新建记录
const handleAdd = () => {
  isEdit.value = false;
  formData.value = {};
  showCrud.value = true;
};

const getOptions = () => {
  axiosInstance.post('/api/basedataOrganization/getPage', {
    current: 1,
    pageSize: 100000
  }).then(res => {
    console.log(res);
    workRoomList.value = [];
    for (const item of res.data.records) {
      if (item.level == 2) {
        workRoomList.value.push(item);
      }
    }
  });

  listFetch();
};

const workOptions = ref([]);


const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const {proxy}: any = getCurrentInstance();

// 打印
const printClick = () => {
  // for (const item of multipleSelection.value) {
  // 	item.id = item.batchNo;
  // }
  const templateName = 'test_print1/LocationMachineQrCodePrint.cpt';
  proxy.$printClick(templateName, multipleSelection.value);
};

// 获取列表数据
const listFetch = () => {
  workOptions.value = []
  lineAll({current: 1, pageSize: 100000}).then((res) => {
    if (res.code === 200) {
      workOptions.value = buildTree(res.data.records.map((item) => {
        return {
          ...item.extension,
          ...item
        };
      }));
    }
  });
};

// 构建树形结构
const buildTree = (items) => {
  const itemMap = {};
  const rootItems = [];
  items.forEach((item) => {
    itemMap[item.id] = {...item, name: item.orgName, children: []};
  });
  items.forEach((item) => {
    if (!item.parentId || item.parentId === '0') {
      rootItems.push(itemMap[item.id]);
    } else {
      if (itemMap[item.parentId]) {
        itemMap[item.parentId].children.push(itemMap[item.id]);
      }
    }
  });

  return rootItems;
};

// const handleDel = (row) => {
//   ElMessageBox.confirm('确定删除该条数据吗？', '提示', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'warning',
//   }).then(async () => {
//     await axiosInstance.delete('/api/basedataProcedure/delete', { data: { ids: [element.id] } }).then(res => {
//       ElMessage.success('删除成功');
//       getData();
//     });
//   }).catch(() => { });
// }
// 编辑记录
const handleEdit = (row: any) => {
  isEdit.value = true;
  formData.value = {...row};
  showCrud.value = true;
};

const resetSearch = () => {
  searchParam.value = {};
  handleSearch();
}

const typeList = ref([
  {label: '自制', value: '0'},
  {label: '内购', value: '1'},
  {label: '外购', value: '2'},
  {label: '租赁', value: '3'},
  {label: '客供', value: '4'}
]);
const getTypeName = (type: string) => {
  const name = typeList.value.find((item: any) => item.value === type);
  return name ? name.label : '';
};
// 动态列和新列的数据
const columns = ref([
  {tableChineseKey: '自定义列1', tableKey: 'tableKey', visible: true},
  {tableChineseKey: '自定义列2', tableKey: 'tableKey', visible: true}
  // 可添加更多默认列
]);
const showAddColumnDialog = ref(false);
const showAddColumnDialog2 = ref(false);
const columnDialogTitle = ref('');
const columnIndexNumber = ref(0);

const newColumn = ref({
  tableChineseKey: '',
  tableKey: '',
  visible: true,
  id: ''
});
// 查询列
const getColumnsList = () => {
  axiosInstance.post('/api/dynamicTableExtension/getPage',
      {page: 1, pageSize: 999, tableName: 'equipment'}
  ).then(res => {
    const {data, code, message} = res;
    if (code === 200) {
      columns.value = data.records;
    }
  });
};
// 新建列
const addColumn = () => {
  console.log('编辑');

  if (newColumn.value.tableKey && newColumn.value.tableChineseKey) {

    if (columnDialogTitle.value === '新建') {
      axiosInstance.post('/api/dynamicTableExtension/save', {
        'frontendType': 'INPUT',
        'tableName': 'equipment',
        'tableKey': newColumn.value.tableKey,
        'tableChineseKey': newColumn.value.tableChineseKey
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('新建列成功');
          getColumnsList();
          // columns.value.push({ ...newColumn.value });
          newColumn.value = {tableKey: '', tableChineseKey: '', visible: true};
          showAddColumnDialog2.value = false;
        }
      });

    } else {
      console.log('编辑');
      axiosInstance.put('/api/dynamicTableExtension/update', {
        'frontendType': 'INPUT',
        'tableName': 'equipment',
        'tableKey': newColumn.value.tableKey,
        'tableChineseKey': newColumn.value.tableChineseKey,
        'id': newColumn.value.id

      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('修改成功');
          getColumnsList();
          showAddColumnDialog2.value = false;

        }
      });

    }

  }
};

// 编辑列
const editColumn = (row: any, index: number) => {
  console.log(row);
  columnIndexNumber.value = index;
  columnDialogTitle.value = '编辑';
  showAddColumnDialog2.value = true;
  newColumn.value.tableChineseKey = row.tableChineseKey;
  newColumn.value.tableKey = row.tableKey;
  newColumn.value.id = row.id;


};

// 删除列
const deleteColumn = (row: any, index: number) => {
  axiosInstance.delete('/api/dynamicTableExtension/delete', {
    data: {
      ids: [row.id]
    }
  }).then(res => {
    if (res.code === 200) {
      getColumnsList();
      ElMessage.success('修改成功');

    }
  });
  // columns.value.splice(index, 1);
};


// 删除列
const handleDel = (row: any) => {
  ElMessageBox.confirm('是否确认删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        axiosInstance.delete('/api/basedataEquipment/delete', {
          data: {
            ids: [row.id]
          }
        }).then(res => {
          if (res.code === 200) {
            handleSearch();
            ElMessage.success('修改成功');

          }
        });
      })

  // columns.value.splice(index, 1);
};

// 保存设备信息
const handleSave = () => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const formDataObject = columns.value.reduce((acc, col) => {
        acc[col.tableKey] = formData.value[col.tableKey];
        return acc;
      }, {});
      console.log(formDataObject);
      formData.value.extension = formDataObject;
      addEquipment(formData.value, (() => {
        console.log('执行了');
        showCrud.value = false;
      }));
      showCrud.value = false;
    }
  });
};
</script>
<style scoped></style>
